package de.pa2.templates;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class VelocityResourceLoader extends ResourceLoader {
	private static final Logger LOG = LoggerFactory
			.getLogger(VelocityResourceLoader.class);
	private ExtendedProperties properties = null;
	private String basedir = null;

	private String[] generateFilename(String template) {
		String[] basedirs = basedir.split(",");
		ArrayList<String> result = new ArrayList<String>();
		for (int i = 0; i < basedirs.length; i++) {
			String[] filenames = VelocityHelper.createFilenames(basedirs[i],
					template);
			for (String filename : filenames) {
				result.add(filename);
			}
		}
		if (LOG.isDebugEnabled()) {
			StringBuilder debug = new StringBuilder();
			debug.append("possible filenames for template '" + template
					+ "' are:");
			for (int i = 0; i < result.size(); i++) {
				if (i > 0)
					debug.append(",");
				debug.append(result.get(i));
			}
			LOG.debug(debug.toString());
		}
		return result.toArray(new String[] {});
	}

	private File[] getFiles(String template) {
		String[] filenames = generateFilename(template);
		File[] result = new File[filenames.length];
		for (int i = 0; i < result.length; i++) {
			result[i] = new File(filenames[i]);
		}
		return result;
	}

	public long getLastModified(Resource resource) {
		File[] files = getFiles(resource.getName());
		for (int i = 0; i < files.length; i++) {
			if (files[i].exists()) {
				return files[i].lastModified();
			}
		}
		return 0;
	}

	public InputStream getResourceStream(String template)
			throws ResourceNotFoundException {
		File[] files = getFiles(template);
		for (int i = 0; i < files.length; i++) {
			if (files[i].exists()) {
				InputStream result;
				try {
					result = new FileInputStream(files[i]);
					return result;
				} catch (FileNotFoundException e) {
					LOG.error("velocity template file '" + template
							+ "' exists, but could not be found???", e);
				}
			}
		}
		return null;
	}

	public void init(ExtendedProperties properties) {
		this.properties = properties;
		this.basedir = this.properties.getString("basedir");
		if (LOG.isDebugEnabled())
			LOG.debug("using basedir=" + this.basedir);
	}

	public boolean isSourceModified(Resource arg0) {
		// TODO implement
		return false;
	}
}
